package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.common.auth.JwtUtils;
import com.leyou.common.auth.Payload;
import com.leyou.common.auth.UserInfo;
import com.leyou.common.constants.UserTokenConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author 虎哥
 */
@Service
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties prop;

    public void login(String username, String password, HttpServletResponse response) {
        // 1.发送请求到用户中心，查询用户
        UserDTO user = null;
        try {
            user = userClient.queryUserByUsernameAndPassword(username, password);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD, e);
        }
        // 3.成功：利用私钥生成JWT
        String token = JwtUtils.generateTokenExpireInMinutes(
                new UserInfo(user.getId(), user.getUsername(), "Guest"),
                prop.getPrivateKey(),
                UserTokenConstants.EXPIRE_MINUTES);
        // 4.要把jwt写再用户cookie
        writeCookie(response, token);
    }

    public UserInfo verify(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 1.获取cookie
            String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
            // 2.解析cookie，获取jwt中的用户信息
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
            // 3.校验黑名单
            String id = payload.getId();
            Boolean exists = redisTemplate.hasKey(id);
            if(BooleanUtils.isTrue(exists)){
                // id存在与黑名单，说明是无效token
                throw new LyException(ExceptionEnum.UNAUTHORIZED);
            }
            // 4.刷新token
            // 4.1.获取token的到期时间
            long remainTime = payload.getExpiration().getTime() - System.currentTimeMillis();
            // 4.2.判断token是否即将到期（剩余有效期是否小于10分钟）
            if(remainTime < UserTokenConstants.MIN_REFRESH_TIMEOUT){
                // 4.3.如果即将到期，就重新生成token
                token = JwtUtils.generateTokenExpireInMinutes(
                        payload.getUserInfo(),
                        prop.getPrivateKey(),
                        UserTokenConstants.EXPIRE_MINUTES);
                // 4.4.写到cookie
                writeCookie(response, token);
            }
            // 4.返回用户信息
            return payload.getUserInfo();
        } catch (Exception e) {
            // 登录失效，返回401
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
    }

    private void writeCookie(HttpServletResponse response, String token) {
        CookieUtils.newCookieBuilder()
                .response(response)
                .name(UserTokenConstants.COOKIE_NAME)
                .value(token)
                .httpOnly(true)
                .domain(UserTokenConstants.DOMAIN)
                .build();
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        // 1.服务端获取cookie
        String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
        if(StringUtils.isBlank(token)){
            return;
        }
        // 2.解析cookie中的token（验证是否有token）
        Payload<Object> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey());

        // 3.记录黑名单
        // 3.1.获取token中的id
        String id = payload.getId();
        // 3.2.获取剩余时间
        long remainTime = payload.getExpiration().getTime() - System.currentTimeMillis();
        // 3.3.记录到redis，时间是token的剩余时间
        redisTemplate.opsForValue().set(id, "1", remainTime, TimeUnit.MILLISECONDS);

        // 4.删除cookie
        CookieUtils.deleteCookie(UserTokenConstants.COOKIE_NAME, UserTokenConstants.DOMAIN, response);
    }
}
